﻿using AutoMapper;
using MediatR;
using SlaughterItem.Common.Domains;
using SlaughterItem.Common.Domains.RBAC;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week01.UsersCommands
{
    public class UsersAddHandler : IRequestHandler<UsersAddCommand, Result>
    {
        IBaseRepository<Users> UsersRep;
        IMapper mapper;

        public UsersAddHandler(IBaseRepository<Users> usersRep, IMapper mapper)
        {
            UsersRep = usersRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 用户的添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(UsersAddCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {

                var UserList = UsersRep.GetAll().Count(x => x.UsersName == request.UsersName && x.UsersPwd == request.UsersPwd && x.IsDel == false);
                if (UserList > 0)
                {
                    result.Code = (int)CommonErrorCode.Added;
                }
                else
                {
                    var res = UsersRep.Add(new Users()
                    {
                        UsersId = 0,
                        UsersName = request.UsersName,
                        UsersPwd = request.UsersPwd,
                        RoleId = request.RoleId,
                        IsDel = false
                    });
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
